<template>
  <el-row>
    <el-divider content-position="left">系统配置</el-divider>
    <el-form
      :inline="true"
      :model="baseformInfo"
      :rules="baseRules"
      ref="baseformref"
      class="demo-form-inline"
      style="margin-left: 20px"
    >
      <el-form-item label="批次名称" prop="batchname">
        <el-input
          v-model="baseformInfo.batchname"
          placeholder="批次名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="测试用例" prop="testcasename">
        <el-select
          v-model="baseformInfo.testcasename"
          placeholder="请选择测试用例"
          @change="handleTestCaseChange"
          style="width: 200px"
        >
          <el-option
            v-for="item in testCaseList"
            :key="item.id"
            :label="item.testCaseName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button type="primary" @click="executeAndSend"
        >发送配置并启动</el-button
      >
    </div>
    <el-divider content-position="left">板卡配置</el-divider>
    <el-col :span="6">
      <el-tree
        ref="treeRef"
        :data="boarddatas"
        show-checkbox
        default-expand-all
        v-model:checkedKeys="treeCheckList"
        node-key="boardNumber"
        highlight-current
        :props="defaultProps"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      >
        <template #default="{ node, data }">
          <span
            v-if="data.id != '0'"
            :class="{
              'board-node': true,
              active: currentBoardId == data.boardNumber,
              hovered: node.isHovered,
            }"
            @mouseenter="node.isHovered = true"
            @mouseleave="node.isHovered = false"
          >
            集成电路板卡- {{ data.boardNumber }}</span
          >
          <span v-else> 板卡列表</span>
        </template>
      </el-tree>
    </el-col>
    <el-divider direction="vertical" />
    <el-col :span="17">
      <div style="text-align: right">
        <el-button type="primary" @click="saveConfig">确定</el-button>
        <el-button type="primary" @click="applyToSameType"
          >一键配置板卡</el-button
        >
      </div>
      <el-divider content-position="left">基础配置</el-divider>
      <el-form
        :model="formInline"
        :rules="rules"
        ref="formRef"
        class="demo-form-inline"
        inline
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="核电阈值" prop="核电阈值">
              <el-input
                v-model="formInline.核电阈值"
                placeholder="请输入核电阈值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁判断次数" prop="闩锁判断次数">
              <el-input
                v-model="formInline.闩锁判断次数"
                placeholder="请输入闩锁判断次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁恢复次数" prop="闩锁恢复次数">
              <el-input
                v-model="formInline.闩锁恢复次数"
                placeholder="请输入闩锁恢复次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁损坏次数" prop="闩锁损坏次数">
              <el-input
                v-model="formInline.闩锁损坏次数"
                placeholder="请输入闩锁损坏次数"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="辅助电磁阀" prop="辅助电磁阀">
              <el-input
                v-model="formInline.辅助电磁阀"
                placeholder="请输入辅助电磁阀"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁判断次数" prop="闩锁判断次数1">
              <el-input
                v-model="formInline.闩锁判断次数1"
                placeholder="请输入闩锁判断次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁恢复次数1" prop="闩锁恢复次数1">
              <el-input
                v-model="formInline.闩锁恢复次数1"
                placeholder="请输入闩锁恢复次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁损坏次数1" prop="闩锁损坏次数1">
              <el-input
                v-model="formInline.闩锁损坏次数1"
                placeholder="请输入闩锁损坏次数"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="20" v-if="currentBoardType === '三路电'">
          <el-col :span="6">
            <el-form-item label="RANK阈值" prop="RANK阈值">
              <el-input
                v-model="formInline.RANK阈值"
                placeholder="请输入RANK阈值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁判断次数" prop="闩锁判断次数2">
              <el-input
                v-model="formInline.闩锁判断次数2"
                placeholder="请输入闩锁判断次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁恢复次数" prop="闩锁恢复次数2">
              <el-input
                v-model="formInline.闩锁恢复次数2"
                placeholder="请输入闩锁恢复次数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="闩锁损坏次数" prop="闩锁损坏次数2">
              <el-input
                v-model="formInline.闩锁损坏次数2"
                placeholder="请输入闩锁损坏次数"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开始地址" prop="开始地址">
              <el-input
                v-model="formInline.开始地址"
                placeholder="请输入开始地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束地址" prop="结束地址">
              <el-input
                v-model="formInline.结束地址"
                placeholder="请输入结束地址"
              />
            </el-form-item>
          </el-col>
          <!-- 占位，使布局完整 -->
          <el-col :span="6"></el-col>
          <el-col :span="6"></el-col>
        </el-row>

        <el-divider content-position="left">板卡状态配置</el-divider>
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="板卡名称" prop="板卡名称">
              <el-input
                v-model="formInline.板卡名称"
                placeholder="请输入板卡名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电源组状态" prop="电源组状态">
              <el-input
                v-model="formInline.电源组状态"
                placeholder="请输入电源组状态"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="损毁配置" prop="损毁配置">
              <el-input
                v-model="formInline.损毁配置"
                placeholder="请输入损毁配置"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="片选配置" prop="片选配置">
              <el-input
                v-model="formInline.片选配置"
                placeholder="请输入片选配置"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电源组加电" prop="电源组加电">
              <el-input
                v-model="formInline.电源组加电"
                placeholder="请输入电源组加电"
              />
            </el-form-item>
          </el-col>
          <!-- 占位，使布局完整 -->
          <el-col :span="12"></el-col>
        </el-row>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { icBoardTypelist } from "@/api/device/ICBoardType";
import { sendControl } from "@/api/device/mqttSend";
import { ElMessage, ElMessageBox } from "element-plus";
import { getTestCaseList } from "@/api/device/testcase";
const props = defineProps({
  datasourceindex: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "ic",
  },
  deviceid: {
    type: String,
    default: "",
  },
});
const baseformref = ref("");
const baseformInfo = reactive({
  batchname: "",
  testcasename: "default",
});
const formRef = ref(null);
const baseRules = reactive({
  batchname: [{ required: true, message: "请输入批次名称", trigger: "blur" }],
});

// 封装表单校验方法
const validateForm = () => {
  if (!formRef.value) return false;
  try {
    return formRef.value.validate();
  } catch (error) {
    ElMessage.error("表单校验失败，请检查输入项");
    return false;
  }
};

// 仅保留模板中使用的表单数据
const formInline = reactive({
  核电阈值: "",
  闩锁判断次数: "",
  闩锁恢复次数: "",
  闩锁损坏次数: "",
  闩锁判断次数1: "",
  闩锁恢复次数1: "",
  闩锁损坏次数1: "",
  闩锁判断次数2: "",
  闩锁恢复次数2: "",
  闩锁损坏次数2: "",
  辅助电磁阀: "",
  RANK阈值: "",
  开始地址: "",
  结束地址: "",
  板卡名称: "",
  电源组状态: "",
  损毁配置: "",
  片选配置: "",
  电源组加电: "",
});
const rules = reactive({
  核电阈值: [{ required: true, message: "请输入核电阈值", trigger: "blur" }],
  闩锁判断次数: [
    { required: true, message: "请输入闩锁判断次数", trigger: "blur" },
  ],
  闩锁恢复次数: [
    { required: true, message: "请输入闩锁恢复次数", trigger: "blur" },
  ],
  闩锁损坏次数: [
    { required: true, message: "请输入闩锁损坏次数", trigger: "blur" },
  ],
  辅助电磁阀: [
    { required: true, message: "请输入辅助电磁阀", trigger: "blur" },
  ],
  闩锁判断次数1: [
    { required: true, message: "请输入闩锁判断次数", trigger: "blur" },
  ],
  闩锁恢复次数1: [
    { required: true, message: "请输入闩锁恢复次数", trigger: "blur" },
  ],
  闩锁损坏次数1: [
    { required: true, message: "请输入闩锁损坏次数", trigger: "blur" },
  ],
  RANK阈值: [{ required: true, message: "请输入RANK阈值", trigger: "blur" }],
  闩锁判断次数2: [
    { required: true, message: "请输入闩锁判断次数", trigger: "blur" },
  ],
  闩锁恢复次数2: [
    { required: true, message: "请输入闩锁恢复次数", trigger: "blur" },
  ],
  闩锁损坏次数2: [
    { required: true, message: "请输入闩锁损坏次数", trigger: "blur" },
  ],
  开始地址: [{ required: true, message: "请输入开始地址", trigger: "blur" }],
  结束地址: [{ required: true, message: "请输入结束地址", trigger: "blur" }],
  板卡名称: [{ required: true, message: "请输入板卡名称", trigger: "blur" }],
  电源组状态: [
    { required: true, message: "请输入电源组状态", trigger: "blur" },
  ],
  损毁配置: [{ required: true, message: "请输入损毁配置", trigger: "blur" }],
  片选配置: [{ required: true, message: "请输入片选配置", trigger: "blur" }],
  电源组加电: [
    { required: true, message: "请输入电源组加电", trigger: "blur" },
  ],
});
const testCaseList = ref([]);
const handleTestCaseChange = (value) => {
  testCaseList.value.forEach((item) => {
    if (item.Name === value) {
      defaultConfig = JSON.parse(item.configurationParameters.value);
      initFormData();
    }
  });
};

// 存储所有板卡的配置数据
const boardConfigs = reactive({});
// 存储树节点选中状态
const treeCheckList = ref([]);
// 记录当前选中板卡的类型
const currentBoardType = ref("");
// 记录当前选中板卡的编号
const currentBoardId = ref(null);
// 添加选中状态变化处理方法
const handleCheckChange = (data, checked, indeterminate) => {
  const boardNumber = data.boardNumber;
  // 如果节点被取消选中且存在配置数据，则从boardConfigs中移除
  if (!checked && boardConfigs[boardNumber]) {
    delete boardConfigs[boardNumber];
    console.log(`已移除板卡 ${boardNumber} 的配置信息`);
  }
};
// 树节点点击事件处理方法
const treeRef = ref(null);
const handleNodeClick = (data) => {
  // 更新当前选中板卡的类型
  currentBoardType.value = data.boardType;
  // 更新当前选中板卡的编号
  currentBoardId.value = data.boardNumber;
  // 回显对应板卡的配置数据
  if (boardConfigs[data.boardNumber]) {
    Object.assign(formInline, boardConfigs[data.boardNumber]);
  } else {
    // 若没有配置数据，重置表单
    //Object.keys(formInline).forEach((key) => {
    //formInline[key] = "";
    //});
    // 若没有配置数据，使用默认数据初始化表单
    initFormData();
  }
};
const executeAndSend = async () => {
  ElMessageBox.confirm("是否发送配置并启动？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    baseformref.value.validate((valid) => {
      if (!valid) {
        return;
      }
      if (Object.keys(boardConfigs).length === 0) {
        ElMessage.warning("请配置板卡信息");
        return;
      }
      //调用发送数据的 API 方法
      sendControl({
        datasourceindex: props.datasourceindex,
        type: props.type,
        deviceid: props.deviceid,
        message: {
          type: "下发配置",
          config: boardConfigs,
          ...baseformInfo,
        },
      }).then((res) => {
        console.log("数据发送成功", res);
        // 可以在这里添加成功提示
      });
    });
  });
};

// 将当前配置应用于同类型板卡的方法
const applyToSameType = () => {
  if (currentBoardId.value !== null && currentBoardType.value) {
    const isValid = validateForm();
    if (!isValid) {
      return;
    }
    boarddatas.value[0].children.forEach((board) => {
      if (board.boardType === currentBoardType.value) {
        boardConfigs[board.boardNumber] = { ...formInline };
        if (!treeCheckList.value.includes(board.boardNumber)) {
          treeCheckList.value.push(board.boardNumber);
        }
      }
    });
    treeRef.value.setCheckedKeys(treeCheckList.value, false);
    console.log("当前配置已应用于同类型板卡");
  } else {
    ElMessage.warning("请选择需要配置的一键类型板卡");
  }
};
// 保存配置方法
const saveConfig = () => {
  if (currentBoardId.value !== null) {
    const isValid = validateForm();
    if (!isValid) {
      return;
    }
    boardConfigs[currentBoardId.value] = { ...formInline };

    console.log("板卡配置已保存:", boardConfigs[currentBoardId.value]);
    const index = treeCheckList.value.indexOf(currentBoardId.value);
    if (index === -1) {
      treeCheckList.value.push(currentBoardId.value);
    }
    treeRef.value.setCheckedKeys(treeCheckList.value, false);
  } else {
    ElMessage.warning("请选择需要配置板卡");
  }
};
const defaultConfig = reactive({
  ID: 0,
  Name: "default",
  configtype: {
    SystemVoltage: 5.0,
    SystemCurrent: 5.0,
    电流配置: [
      {
        核电参数: {
          电路类型: 0,
          阈值: 5.0,
          闩锁判断次数: 5,
          闩锁恢复次数: 5,
          闩锁损坏次数: 5,
        },
        辅助电参数: {
          电路类型: 1,
          阈值: 5.0,
          闩锁判断次数: 5,
          闩锁恢复次数: 5,
          闩锁损坏次数: 5,
        },
        BANK电: {
          电路类型: 2,
          阈值: 5.0,
          闩锁判断次数: 5,
          闩锁恢复次数: 5,
          闩锁损坏次数: 5,
        },
        器件类型: 0,
        startaddress: "00 00 00 00",
        endaddress: "00 FF 00 00",
      },
      {
        核电参数: {
          电路类型: 0,
          阈值: 5.0,
          闩锁判断次数: 5,
          闩锁恢复次数: 5,
          闩锁损坏次数: 5,
        },
        辅助电参数: {
          电路类型: 1,
          阈值: 5.0,
          闩锁判断次数: 5,
          闩锁恢复次数: 5,
          闩锁损坏次数: 5,
        },
        BANK电: {
          电路类型: 0,
          阈值: 0.0,
          闩锁判断次数: 0,
          闩锁恢复次数: 0,
          闩锁损坏次数: 0,
        },
        器件类型: 0,
        startaddress: "00 00 00 00",
        endaddress: "00 FF 00 00",
      },
    ],
    板卡状态配置: [
      {
        芯片状态配置: "0x00FFFFFFFFFF",
        电源组状态配置: 63,
        电源组加电配置: 63,
        片选使能: "0x00FFFFFFFFFF",
      },
      {
        芯片状态配置: "0x00FFFFFFFFFF",
        电源组状态配置: 63,
        电源组加电配置: 63,
        片选使能: "0x00FFFFFFFFFF",
      },
    ],
  },
  create_time: "2025-07-30T16:10:58.053704+08:00",
  last_update_time: "2025-07-30T16:10:58.0537051+08:00",
});
const defaultProps = {
  children: "children",
  label: "label",
};
// 初始化表单数据
const initFormData = () => {
  const currentConfig = defaultConfig.configtype;
  const currentElecConfig = currentConfig.电流配置[0]; // 取第一个电流配置对象
  const currentStatusConfig = currentConfig.板卡状态配置[0]; // 取第一个状态配置对象

  // 填充核电参数
  formInline.核电阈值 = currentElecConfig.核电参数.阈值;
  formInline.闩锁判断次数 = currentElecConfig.核电参数.闩锁判断次数;
  formInline.闩锁恢复次数 = currentElecConfig.核电参数.闩锁恢复次数;
  formInline.闩锁损坏次数 = currentElecConfig.核电参数.闩锁损坏次数;

  // 填充辅助电参数
  formInline.辅助电磁阀 = currentElecConfig.辅助电参数.阈值;
  formInline.闩锁判断次数1 = currentElecConfig.辅助电参数.闩锁判断次数;
  formInline.闩锁恢复次数1 = currentElecConfig.辅助电参数.闩锁恢复次数;
  formInline.闩锁损坏次数1 = currentElecConfig.辅助电参数.闩锁损坏次数;

  // 填充BANK电参数
  formInline.RANK阈值 = currentElecConfig.BANK电.阈值;
  formInline.闩锁判断次数2 = currentElecConfig.BANK电.闩锁判断次数;
  formInline.闩锁恢复次数2 = currentElecConfig.BANK电.闩锁恢复次数;
  formInline.闩锁损坏次数2 = currentElecConfig.BANK电.闩锁损坏次数;

  // 填充地址信息
  formInline.开始地址 = currentElecConfig.startaddress;
  formInline.结束地址 = currentElecConfig.endaddress;

  // 填充板卡状态配置
  formInline.板卡名称 = defaultConfig.Name;
  formInline.电源组状态 = currentStatusConfig.电源组状态配置;
  formInline.损毁配置 = currentStatusConfig.芯片状态配置;
  formInline.片选配置 = currentStatusConfig.片选使能;
  formInline.电源组加电 = currentStatusConfig.电源组加电配置;
};
const boarddatas = ref([]);
icBoardTypelist({ datasourceindex: props.datasourceindex }).then((res) => {
  boarddatas.value = [
    {
      id: 0,
      label: "板卡列表",
      children: res.sort((a, b) => a.id - b.id),
    },
  ];
  if (res.length > 0) {
    currentBoardId.value = res[0].boardNumber;
    currentBoardType.value = res[0].boardType;
    initFormData();
  }
});
getTestCaseList({ datasourceindex: props.datasourceindex, type: "ic" }).then(
  (res) => {
    testCaseList.value = res;
    res.forEach((item) => {
      if (item.testCaseName === "default") {
        defaultConfig = JSON.parse(item.configurationParameters.value);
      }
    });
  }
);
</script>
<style scoped>
.vertical-divider {
  height: 100%;
  border-left: 1px solid #dcdfe6; /* 竖线颜色和宽度 */
}
.board-node {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.board-node.active {
  background-color: #409eff;
  color: white;
  font-weight: bold;
}

.board-node.hovered {
  background-color: #ecf5ff;
  color: #409eff;
}

.root-node {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  display: block;
}
</style>
